package org.brownflat.dbinit.upgrade;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>Database Init &copy Rupert Jones 2013</p>
 *
 * @author rup
 */
public class JavaUpgradeSource extends AbstractUpgradeSource {
    private String packageName;
    private Upgrade initial = new DummyZeroUpgrade();
    private UpgradeFinder upgradeFinder = new UpgradeClassFinder();

    public JavaUpgradeSource(String packageName) {
        this.packageName = packageName;
    }

    @Override
    public List<Upgrade> getUpgrades() {
        List<Upgrade> upgrades = new ArrayList<Upgrade>();
        try {
            Class<Upgrade>[] upgradeClasses = (Class<Upgrade>[]) upgradeFinder.find(packageName, null);
            for(Class<Upgrade> thisClass : upgradeClasses) {
                upgrades.add(thisClass.newInstance());
            }
        } catch (InstantiationException ie) {
            throw new RuntimeException("Upgrade classes must have a default constructor", ie);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        upgrades.add(initial);
        sort(upgrades);
        return upgrades;
    }

    @Override
    public void setInitialUpgrade(Upgrade initial) {
        this.initial = initial;
    }
}
